package com.financing.wap.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.financing.wap.dao.IUserAgreeAgreementDao;
import com.financing.wap.dao.IUserDao;
import com.financing.wap.dto.UserAgreeAgreementDTO;
import com.financing.wap.dto.UserDTO;
import com.financing.wap.service.IUserAgreeAgreeMentService;

@Service("userAreeAgreementService")
public class UserAgreeAgreementServiceImpl implements IUserAgreeAgreeMentService {

	@Autowired
	private IUserAgreeAgreementDao userAgreeAgreementDao;
	
	@Autowired
	private IUserDao userDao;

	@Override
	public UserAgreeAgreementDTO getUserAgreeAgreementById(int id) throws Exception {
		UserAgreeAgreementDTO dto = new UserAgreeAgreementDTO();
		dto.setId(id);
		List<UserAgreeAgreementDTO> list = userAgreeAgreementDao.queryUserAgreeAgreement(dto);
		if(list!= null && (!list.isEmpty())){
			return list.get(0);
		}
		return null;
	}

	@Override
	public UserAgreeAgreementDTO getUserAgreeAgreementByUserLoginName(String loginName) throws Exception {
		UserAgreeAgreementDTO dto = new UserAgreeAgreementDTO();
		dto.setFpFaLoginName(loginName);
		List<UserAgreeAgreementDTO> list = userAgreeAgreementDao.queryUserAgreeAgreement(dto);
		if(list!= null && (!list.isEmpty())){
			return list.get(0);
		}

		return null;
	}

	@Override
	public UserAgreeAgreementDTO addUserAgreeAgreement(UserAgreeAgreementDTO dto) throws Exception {
		
		UserAgreeAgreementDTO tmp = getUserAgreeAgreementByUserLoginName(dto.getFpFaLoginName());
		
		UserDTO user = new UserDTO();
		user.setLoginName(dto.getFpFaLoginName());
		user = userDao.queryUserLoginName(user);
		
		if(null!= user && null!=user.getId()){
			dto.setFpFaId(user.getId());
		}else{
			return null;
		}
		
		//数据库中没有此用户的同意协议记录则添加,有则更新
		if(tmp == null){
			dto.setCreateBy(dto.getFpFaLoginName());
			dto.setUpdateBy(dto.getFpFaLoginName());
			dto.setId(userAgreeAgreementDao.addUserAgreeAgreement(dto));
		}else{
			dto.setId(tmp.getId());
			userAgreeAgreementDao.updateUserAgreeAgreement(dto);
		}
		return dto;
	}

	
}
